import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Modal, Radio } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data'
import { getPointsAccountList, freezeAssetAccount, unFreezeAssetAccount } from './service'
import TableTitle from '../../../components/TableTitle'

export default () => {
  const { TextArea } = Input;
  // 锁定冻结模态框控制
  const [isFrozenModalVisible, setIsFrozenModalVisible] = useState(false);
  // 存储状态:冻结还是解冻
  const [isFreeze, setIsFreeze] = useState('');
  // 确认 获取原因表单
  const reasonFormRef: any = React.createRef();
  // 存储当前行的值
  const [accountRecord, setAccountRecord] = useState({});

  // 处理冻结用户
  const handleFrozenInfoOk = async () => {
    // 表单验证
    reasonFormRef.current.validateFields().then(async () => {
      // 获取新增表单的值
      var reponse = reasonFormRef.current?.getFieldsValue()
      // 所需参数客户号 判断操作参数status
      const { custNo, status } = accountRecord
      // 所需参数原因
      const { refusalCause: reason } = reponse
      let data = { custNo, reason, type: 'POINT' }
      console.log(data);

      // 判断是冻结还是解冻
      status === '0' ? await freezeAssetAccount(data) : status === '3' ? await unFreezeAssetAccount(data) : ''
      // 重置表单
      reasonFormRef.current.resetFields()
      // 表格重刷新
      actionRef.current?.reload()
      // 关闭模态框
      setIsFrozenModalVisible(false)
    }).catch(() => { })
  }

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) =>
    <a key={record.custNo} onClick={() => { handleFreeze(record) }}>
      {record.status === '0' ? '冻结' : record.status === '3' ? '解冻' : ''}
    </a>

  // 金额行数据 自定义靠右
  const balanceRender: any = (text: any, record: any, index: number) =>
    [<p key={record.custNo} style={{ textAlign: 'right', margin: 0 }}>
      {typeof text === 'number' ? text.toFixed(6) : null}
    </p>]

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? item.render = actionRender : undefined
    item.dataIndex === 'balance' ? item.render = balanceRender : undefined
  });

  // 冻结解冻
  const handleFreeze = (record: any) => {
    console.log(record);
    // 把值存起来用于冻结解冻接口
    setAccountRecord(record)
    setIsFrozenModalVisible(true)
    // 改变模态框里面冻结解冻的显示状况
    record.status === '0' ? setIsFreeze('freeze') : record.status === '3' ? setIsFreeze('unFreeze') : ''
  }
  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title='积分账户信息' />}
        scroll={{ x: 900 }}
        bordered
        // 表头
        columns={columns}
        actionRef={actionRef}
        // 请求获取的数据
        request={
          async params => {
            console.log(params);
            let data = await getPointsAccountList({ ...params, pageNum: params.current })
            console.log('😒', data);
            const result = {
              data: data.body.list,
              total: data.body.total,
            }
            return result;
          }
        }
        rowKey="acNo"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
      />
      {/* 冻结模态框 */}
      <Modal
        title={
          <div>
            <span>户名: {accountRecord.acName}</span>
            <span style={{ marginLeft: 20, marginRight: 20 }}>账号: {accountRecord.acNo}</span>
          </div>}
        centered
        visible={isFrozenModalVisible}
        onOk={handleFrozenInfoOk}
        onCancel={() => {
          setIsFrozenModalVisible(false),
            // 重置表单
            reasonFormRef.current.resetFields()
        }}
      >
        <Radio.Group value={isFreeze} disabled={true} style={{ marginBottom: 24 }}>
          <Radio value={'freeze'}>冻结</Radio>
          <Radio value={'unFreeze'}>解冻</Radio>
        </Radio.Group>
        <Form
          name="basic"
          ref={reasonFormRef}
          wrapperCol={{ span: 24 }}
          autoComplete="off"
        >
          <Form.Item
            key="refusalCause"
            name="refusalCause"
            rules={[{
              required: true,
              whitespace: true,
              message: '请填写原因'
            }]}
          >
            <TextArea rows={4} placeholder="请输入原因" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};